<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="标准编号" value="1" />
							<el-option label="标准名称" value="2" />
							<el-option label="项目负责人" value="3" />
							<el-option label="联系人" value="4" />
							<el-option label="提交人" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-space v-auth="'M003_A'" style="width: 100%; justify-content: flex-end">
			<el-space>
				<el-button type="primary" @click="handleAddNew">新增</el-button>
			</el-space>
		</el-space>
		<el-table v-loading="state.dataListLoading" :data="dataList" stripe class="layout-table" border @selection-change="selectionChangeHandle">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="reviewYear" label="所属年份" header-align="center" align="center" width="110" resizable sortable></el-table-column>
			<el-table-column prop="standardNumber" label="标准编号" header-align="center" align="center" width="140" resizable sortable></el-table-column>
			<el-table-column
				prop="standardProjectName"
				label="标准名称"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="contactName" label="联系人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="contactTel" label="联系电话" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="projectLeader" label="项目负责人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="reviewType" label="复审来源" header-align="center" align="center" width="110" resizable sortable>
				<template #default="scope">
					<span>{{ scope.row.reviewType == 0 ? '计划内' : '计划外' }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="reviewStage" label="复审阶段" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ reviewStage.filter(item => item.code === scope.row.reviewStage)[0].name }}</span>
					<!-- <span v-if="scope.row.reviewStage == 4">审核完毕</span> -->
				</template>
			</el-table-column>
			<el-table-column prop="reviewStatus" label="复审状态" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T015', scope.row.reviewStatus) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="remark" label="复审结论" header-align="center" align="center" min-width="200" resizable sortable>
				<template #default="scope">
					<span v-if="scope.row.remark">{{ reviewResult.filter(item => item.code === scope.row.remark)[0].name }}</span>
					<!-- <span>{{ scope.row.remark }}</span> -->
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="130">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handleView(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="scope.row.reviewStage == '0'"
						v-auth="'M003_Apply'"
						:size="16"
						color="#1491FF"
						title="复审申报"
						style="cursor: pointer; margin: 0 6px"
						@click="editHandle(scope.row)"
					>
						<Edit />
					</el-icon>
					<el-icon
						v-auth="'M003_DownloadPdf'"
						:size="16"
						color="#1491FF"
						title="生成pdf"
						style="cursor: pointer; margin: 0 6px"
						@click="handleExport(scope.row)"
					>
						<Document />
					</el-icon>
					<el-icon
						v-if="scope.row.reviewType != 0"
						v-auth="'M003_D'"
						:size="16"
						color="#1491FF"
						title="删除"
						style="cursor: pointer; margin: 0 6px"
						@click="deleteHandle(scope.row)"
					>
						<Delete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<addDialog v-model="showAddDialog" :edit-id="editId" :is-view="isView" :is-audit="false" :info="standardInfo" @submit-success="addSuccess">
		</addDialog>
	</el-card>
</template>
<script setup lang="ts">
import { getDeadline } from '@/api/declare'
import { getList, reviewDelete } from '@/api/fushen/declare'
import { StandardInfo } from '@/interface/review'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from '../components/addDialog.vue'

const route = useRoute()
const pendingStatus = route.query.pendingStatus

const userStore = useUserStore()
const dictionaryStore = useDictionaryStore()
const reviewResult = dictionaryStore.getDictionaryByCode('T0035')
const reviewStage = dictionaryStore.getDictionaryByCode('T0026')

const state = reactive({
	queryForm: {
		standardNumber: '',
		standardProjectName: '',
		responsiblePerson: '',
		contactName: '',
		applyYear: '',
		reviewAddtype: '',
		reviewYear: '',
		userName: '',
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null
})
const dataList = ref([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const standardInfo = ref<StandardInfo | null>(null)
const isDead = ref<boolean>(false)

watch(
	() => showAddDialog.value,
	newVal => {
		if (!newVal) {
			standardInfo.value = null
			editId.value = ''
			isView.value = false
		}
	}
)

const handleView = (row: any) => {
	standardInfo.value = row
	isView.value = true
	editId.value = row.id
	showAddDialog.value = true
}

const editHandle = (row: any) => {
	standardInfo.value = row
	editId.value = row.id
	showAddDialog.value = true
}

const getDataList = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	if (state.keyword && !state.keyType) {
		ElMessage({
			type: 'warning',
			message: '请选择关键词类型'
		})
		return
	}
	switch (state.keyType) {
		case '1':
			state.queryForm.standardNumber = state.keyword
			break
		case '2':
			state.queryForm.standardProjectName = state.keyword
			break
		case '3':
			state.queryForm.responsiblePerson = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
		case '5':
			state.queryForm.userName = state.keyword
			break
	}
	state.dataListLoading = true
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	state.queryForm.applyYear = ''
	state.queryForm.reviewAddtype = ''
	state.queryForm.reviewYear = ''
	state.queryForm.pendingStatus = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

const handleAddNew = () => {
	if (!isDead.value) {
		showAddDialog.value = true
		editId.value = ''
	} else {
		ElMessage.error('超过申报截止时间 ，不可申报！')
	}
}
const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	reset()
}

const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const deleteHandle = (row: any) => {
	ElMessageBox.confirm('确定删除该条数据?', '提示', {}).then(() => {
		reviewDelete({
			id: row.id
		}).then(() => {
			ElMessage.success('删除成功')
			getDataList()
		})
	})
}

const handleExport = (row: any) => {
	axios({
		method: 'post',
		url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/review/exportPdf',
		headers: {
			'Content-Type': 'application/json;charset=UTF-8',
			Authorization: userStore.token
		},
		data: {
			id: row.id
		},
		responseType: 'blob'
	})
		.then(response => {
			ElMessage.success('操作成功，文件已开始下载')
			const blob = new Blob([response.data], {
				type: 'application/pdf'
			})
			const url = window.URL.createObjectURL(blob)
			const a = document.createElement('a')
			a.href = url
			a.download = '复审项目导出文件.pdf'
			a.click()
			window.URL.revokeObjectURL(url)
		})
		.catch(error => {
			console.error('导出失败:', error)
		})
}

const getTime = (year: string) => {
	getDeadline({
		settingYear: year,
		activeStatus: 0,
		stageCode: 'Review',
		remark: '',
		preparationType: '',
		pageIndex: 1,
		pageSize: 100
	}).then(res => {
		const data = res.data.list || []
		const deadLineTime = data.find(item => item.stageCode === 'Review' && item.activeStatus === 0).deadLineTime || ''
		if (deadLineTime) {
			//判断当前时间大于deadLineTime，则为已截止
			const nowTime = new Date().getTime()
			const deadLine = new Date(deadLineTime).getTime()
			if (nowTime > deadLine) {
				isDead.value = true
			} else {
				isDead.value = false
			}
		} else {
			isDead.value = false
		}
	})
}
onMounted(() => {
	getDataList()
	const year = new Date().getFullYear()
	getTime(year.toString())
})
</script>
